//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  //跳转到个人信息页面
  personalInfo: function() {
    wx.navigateTo({
      url: '../personinfo/personinfo'
    })
  },

  onLoad: function () {
    //显示转发
    wx.showShareMenu({
      withShareTicket: true
    })

    console.log("start")
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      console.log(1)
      this.login()
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          console.log(3)
          this.login()
        }
      })
    }
    console.log("end")
  },

  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  login: function () {
    //if (wx.getStorageSync('sessionkey')) return;
    var that = this;
    console.log(that.data.userInfo.nickName);
    // 登录注册用户信息并获取sessionId
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res.code)
        wx.request({
          url: 'https://api.joinme.org.cn/jm/wechat/user/login/code',
          header: {
            'Content-Type': 'charset=utf-8'
          },
          data: {
            code: res.code,
            nickName: that.data.userInfo.nickName,
            avatarUrl: that.data.userInfo.avatarUrl,
            gender: that.data.userInfo.gender,
            province: that.data.userInfo.province,
            city: that.data.userInfo.city,
            country: that.data.userInfo.country,
          },
          success: function (res) {
            console.log(res)
            wx.setStorageSync('sessionkey', res.data.data.sessionId)
          },
          
        })
      },

      fail: function () {
        console.log("登录时网络错误")
      }
    })

  },
})
